package xdu.lz.stage5_jucUtils.chapter3_exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created at 2019/10/19 0019 上午 11:03
 */
public class Exchanger4 {
    public static void main(String[] args) {

        Exchanger<Integer> exchanger = new Exchanger<>();
        /**
         * 一直交换数据
         */
        new Thread(() -> {
            try {
                AtomicReference<Integer> ref = new AtomicReference<>(1);
                while (true) {
                    ref.set(exchanger.exchange(ref.get()));
                    System.out.println("T1 receive:" + ref.get());
                    Thread.sleep(300);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T1").start();

        new Thread(() -> {
            try {
                AtomicReference<Integer> ref = new AtomicReference<>(2);
                while (true) {
                    ref.set(exchanger.exchange(ref.get()));
                    System.out.println("T2 receive:" + ref.get());
                    Thread.sleep(400);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2").start();
    }
}
